<template>
  <div>
    <ul>
      <li v-for="item of msgList" :key="item.id">
        <p>
          <span>{{ item.user }}</span>
          <span>{{ new Date(item.dateTime) }}</span>
        </p>
        <p>消息：{{ item.msg }}</p>
      </li>
    </ul>
    <input type="text" placeholder="输入消息" v-model="msg" />
    <button @click="sendMsg()">发送消息</button>
  </div>
</template>

<script>
//1、实例化websocket实例
const ws = new WebSocket("ws://10.24.11.65:8000");
export default {
  data() {
    return {
      msg: "",
      username: "",
      msgList: [],
    };
  },
  mounted() {
    this.username = localStorage.getItem("username");
    if (!this.username) {
      this.$router.push("/login");
      return;
    }
    //2、绑定websocket事件处理函数
    ws.addEventListener("open", this.handleWsOpen.bind(this), false); //打开websocket
    ws.addEventListener("close", this.handleWsClose.bind(this), false); //关闭websocket
    ws.addEventListener("error", this.handleWsError.bind(this), false); //处理error
    ws.addEventListener("message", this.handleWsMessage.bind(this), false); //接收广播回来的消息数据
  },
  methods: {
    //4、取出信息
    sendMsg() {
      const msg = this.msg;
      //判断信息是不是空格
      if (!msg.trim().length) {
        return;
      }
      //5、调用ws.send函数 发送数据,传递只能是字符串
      ws.send(
        JSON.stringify({
          id: new Date().getTime(),
          msg: this.msg,
          user: this.username,
          dateTime: new Date().getTime(),
        })
      );
      this.msg=''
    },
    //3、定义事件处理函数
    handleWsOpen(e) {
      console.log("websocket open:", e);
    },
    handleWsClose(e) {
      console.log("websocket close:", e);
    },
    handleWsError(e) {
      console.log("websocket error:", e);
    },
    handleWsMessage(e) {
        const msg= JSON.parse(e.data)
        //6、接收广播回来的数据
        this.msgList.push(msg)
    },
  },
};
</script>
